CREATE OR REPLACE FUNCTION MAY_RESERVE(USER_ID VARCHAR(255), RESOURCE_INPUT INTEGER, LIBRARY_INPUT VARCHAR(255)) RETURNS BOOLEAN AS $$
DECLARE
	TOTAL_UNITS INTEGER;
	RESERVED_UNITS INTEGER;
BEGIN
	IF HAS_RESERVATION(USER_ID, RESOURCE_INPUT, LIBRARY_INPUT) THEN
		RETURN FALSE;
	END IF;

	SELECT COUNT(*) INTO TOTAL_UNITS
		FROM UNIT U
		WHERE U.LIBRARY_ID = LIBRARY_INPUT AND U.RESOURCE_ID = RESOURCE_INPUT;

	SELECT COUNT(*) INTO RESERVED_UNITS
		FROM RESERVATION R
		WHERE R.LIBRARY_ID = LIBRARY_INPUT AND R.RESOURCE_ID = RESOURCE_INPUT;

	RETURN RESERVED_UNITS < TOTAL_UNITS;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION HAS_RESERVATION(USER_INPUT VARCHAR(255), RESOURCE_INPUT INTEGER, LIBRARY_INPUT VARCHAR(255)) RETURNS BOOLEAN AS $$
BEGIN
	RETURN 0 < (SELECT COUNT(*) FROM RESERVATION R
			WHERE R.LIBRARY_ID = LIBRARY_INPUT AND R.RESOURCE_ID = RESOURCE_INPUT AND R.USER_ID = USER_INPUT);
END;
$$ LANGUAGE plpgsql;
